package com.ihd.ihardware.view.lock.view;

import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ihd.ihardware.R;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.common.widget.FullProgressView;
import com.ihd.ihardware.databinding.ActivityLockBinding;
import com.ihd.ihardware.pojo.DeviceListRes;
import com.ihd.ihardware.view.lock.viewmodel.LockViewModel;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.bgabanner.BGABanner;
import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.utils.BLEUtils;
import cn.wowjoy.commonlibrary.utils.CommonUtils;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.HexUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import cn.wowjoy.commonlibrary.widget.MDialog;
import cn.wowjoy.commonlibrary.widget.titlebar.TitleBar;

import static com.ihd.ihardware.common.AppConstans.Lock_Notify_Character_UUID;
import static com.ihd.ihardware.common.AppConstans.Lock_Service_UUID;
import static com.ihd.ihardware.common.AppConstans.Lock_Write_Character_UUID;
import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;

public class LockActivity extends BaseActivity<ActivityLockBinding, LockViewModel> {
    private List<DeviceListRes.DataBean.ListBean> mDeviceStatus = new ArrayList<>();
    private int currIndex = 0;
    private Dialog waitDialog;
    private BleConnectOptions options = new BleConnectOptions.Builder()
            .setConnectTimeout(3000)
            .setServiceDiscoverTimeout(3000)
            .build();
    private Handler handler;
    private MDialog mBottomDG;
    private MDialog mDG;
    private BluetoothStateListener mBluetoothStateListener;

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(false).init();

        mDeviceStatus = (List<DeviceListRes.DataBean.ListBean>) getIntent().getSerializableExtra("locks");

        binding.mtitlebar.setLeftImageResource(R.drawable.lock_nb_back);
        binding.mtitlebar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.mtitlebar.addAction(new TitleBar.Action() {
            @Override
            public String getText() {
                return null;
            }

            @Override
            public int getDrawable() {
                return R.drawable.lock_nb_link;
            }

            @Override
            public void performAction(View view) {
                mDG = DialogUtils.alertDialog(LockActivity.this, MDialog.DG_TYPE.SCALERT, "解除绑定后将无法开锁，您确定要解绑蓝牙锁？", "我再想想", "确认解绑", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDG.cancel();
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDG.cancel();
                        viewModel.unbind(mDeviceStatus.get(currIndex).getId());
                    }
                });
            }
        });
        binding.mtitlebar.addAction(new TitleBar.Action() {
            @Override
            public String getText() {
                return null;
            }

            @Override
            public int getDrawable() {
                return R.drawable.lock_nb_add;
            }

            @Override
            public void performAction(View view) {
                Intent mIntent = new Intent(LockActivity.this, LockBindingActivity.class);
                startActivity(mIntent);
            }
        });

        mBluetoothStateListener = new BluetoothStateListener() {
            @Override
            public void onBluetoothStateChanged(boolean openOrClosed) {
                if (openOrClosed)
                    searchNow();
            }
        };
        BLEUtils.getInstance().registerBluetoothStateListener(mBluetoothStateListener);
        searchNow();

        binding.lockHis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(LockActivity.this, LockHisActivity.class);
                mIntent.putExtra("equipmentId", mDeviceStatus.get(currIndex).getId());
                startActivity(mIntent);
            }
        });

        binding.zwInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(LockActivity.this, LockZWInputActivity.class);
                startActivity(mIntent);
            }
        });

        binding.modifyName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomDG = DialogUtils.lockInputDialog(LockActivity.this, mDeviceStatus.get(currIndex).getNickname());
                mBottomDG.setMsgCallback(new MDialog.interfaceEdit() {
                    @Override
                    public void Receive(String message) {
                        mDeviceStatus.get(currIndex).setNickname(message);
                        viewModel.update(mDeviceStatus.get(currIndex).getId(), message);
                    }
                });
            }
        });

        binding.bannerGuideContent.setData(R.layout.activity_lock_single, mDeviceStatus, null);
        binding.bannerGuideContent.setAdapter(new BGABanner.Adapter<View, DeviceListRes.DataBean.ListBean>() {
            @Override
            public void fillBannerItem(BGABanner banner, View itemView, @Nullable DeviceListRes.DataBean.ListBean model, int position) {
                TextView battery = (TextView) itemView.findViewById(R.id.battery);
                battery.setText("电量剩余" + model.getBattery() + "%");
                FullProgressView pgView = (FullProgressView) itemView.findViewById(R.id.sportview);
                pgView.setProgress(model.getBattery());
                TextView desc = (TextView) itemView.findViewById(R.id.desc);
                desc.setText(model.getNickname());
                TextView status = (TextView) itemView.findViewById(R.id.status);
                ImageView lock = (ImageView) itemView.findViewById(R.id.lock);
                if (model.getStatus() == 0) {
                    lock.setImageResource(R.drawable.lock_icon_unline);
                    status.setVisibility(View.INVISIBLE);
                } else if (model.getStatus() == 1) {
                    lock.setImageResource(R.drawable.lock_icon_open);
                    status.setVisibility(View.VISIBLE);
                } else {
                    lock.setImageResource(R.drawable.lock_icon_close);
                    status.setVisibility(View.INVISIBLE);
                }
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BLEUtils.writePsw(CommonUtils.stringToMac(model.getMac()), "A50A02080808080808", "", Lock_Service_UUID, Lock_Write_Character_UUID);
                    }
                });
            }
        });
        binding.bannerGuideContent.getViewPager().addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                Message message = handler.obtainMessage();
                message.what = 10;
                message.arg1 = position;
                handler.sendMessageDelayed(message, 1500);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state != 0) {
                    handler.removeMessages(10);
                }
            }
        });

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                int arg1 = msg.arg1;
                int what = msg.what;
                if (what == 10) {
                    BLEUtils.closeNotify(CommonUtils.stringToMac(mDeviceStatus.get(currIndex).getMac()), Lock_Service_UUID, Lock_Notify_Character_UUID);
                    currIndex = arg1;
                    connect();
                    mDeviceStatus.get(currIndex).setBattery(0);
                    mDeviceStatus.get(currIndex).setStatus(0);
                    binding.bannerGuideContent.getViewPager().getAdapter().notifyDataSetChanged();
                }
            }
        };

        LiveEventBus.get()
                .with("onNotify", String.class)
                .observe(this, new Observer<String>() {
                    @Override
                    public void onChanged(@Nullable String s) {
//                        Log.e("onNotify onChanged", s);
                        if (s.contains(":")) {
                            BLEUtils.writePsw(s, "A50403", "", Lock_Service_UUID, Lock_Write_Character_UUID);
                        } else {
                            if (s.startsWith("5A08")) {
                                int battery = HexUtils.byteToInt(HexUtils.hexStringToBytes(s.substring(6, 8))[0]);
                                boolean lockStatus = s.substring(12, 14).equals("00");
                                mDeviceStatus.get(currIndex).setBattery(battery);
                                mDeviceStatus.get(currIndex).setStatus(lockStatus ? 1 : 2);
                                binding.bannerGuideContent.getViewPager().getAdapter().notifyDataSetChanged();
                            } else if (s.startsWith("5A05")) {
                                viewModel.addLockRecord(mDeviceStatus.get(currIndex).getId());
                                BLEUtils.writePsw(CommonUtils.stringToMac(mDeviceStatus.get(currIndex).getMac()), "A50403", "", Lock_Service_UUID, Lock_Write_Character_UUID);
                            }
                        }
                    }
                });

        setRx(AppConstans.NICK, new BaseConsumer<DeviceListRes>() {
            @Override
            protected void onStart() {
                waitDialog = DialogUtils.waitingDialog(LockActivity.this);
            }

            @Override
            protected void onSuccess(DeviceListRes mLiveData) {
                DialogUtils.dismiss(LockActivity.this);
                SPUtils.putString(AppConstans.DEVICES, new Gson().toJson(mLiveData.getData().getList(), new TypeToken<List<DeviceListRes.DataBean.ListBean>>() {
                }.getType()));
                binding.bannerGuideContent.getViewPager().getAdapter().notifyDataSetChanged();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(LockActivity.this, error.getMessage());
                DialogUtils.dismiss(LockActivity.this);
            }
        });

        setRx(AppConstans.UNBIND, new BaseConsumer<DeviceListRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(DeviceListRes mLiveData) {
                DialogUtils.successDialog(LockActivity.this, MDialog.DG_TYPE.SUCCESS, R.drawable.toasticon_suc, "解除成功");
                SPUtils.putString(AppConstans.DEVICES, new Gson().toJson(mLiveData.getData().getList(), new TypeToken<List<DeviceListRes.DataBean.ListBean>>() {
                }.getType()));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 1100);
            }

            @Override
            protected void onError(Throwable error) {
            }
        });
        connect();
    }

    private void connect() {
        waitDialog = DialogUtils.waitingDialog(LockActivity.this);
        BLEUtils.getInstance().connect(CommonUtils.stringToMac(mDeviceStatus.get(currIndex).getMac()), options, new BleConnectResponse() {
            @Override
            public void onResponse(int code, BleGattProfile data) {
                if (code == REQUEST_SUCCESS) {
                    BLEUtils.openNotify(CommonUtils.stringToMac(mDeviceStatus.get(currIndex).getMac()), Lock_Service_UUID, Lock_Notify_Character_UUID);
                } else {
                    ToastUtils.showLong(LockActivity.this, getString(R.string.conn_fail));
                    BLEUtils.getInstance().disconnect(CommonUtils.stringToMac(mDeviceStatus.get(currIndex).getMac()));
                }
                DialogUtils.dismiss(LockActivity.this);
            }
        });
    }

    private void searchNow() {
        BLEUtils.getInstance().search(new SearchRequest.Builder().searchBluetoothLeDevice(86400000).build(), new SearchResponse() {
            @Override
            public void onSearchStarted() {
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
            }

            @Override
            public void onSearchStopped() {
            }

            @Override
            public void onSearchCanceled() {
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_lock;
    }

    @Override
    protected Class getViewModelClass() {
        return LockViewModel.class;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BLEUtils.closeNotify(CommonUtils.stringToMac(mDeviceStatus.get(currIndex).getMac()), Lock_Service_UUID, Lock_Notify_Character_UUID);
        BLEUtils.getInstance().unregisterBluetoothStateListener(mBluetoothStateListener);
        BLEUtils.getInstance().stopSearch();
    }
}
